# Create your views here.
import base64
import json
import logging
import os
from datetime import datetime
from typing import Dict, List

import pika
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.urls import reverse

from chapter.file import put_object_from_file, set_file_name
from pang5_web.func import get_uid
from pang5_web.settings import IMG_URL
from pang5_web.settings import PLATFORMS, RABBITMQ_HOST, RABBITMQ_PASSWORD, RABBITMQ_POST, RABBITMQ_USER, \
    PLATFORM_STATUS_PUBLISHING
from pang5_web.utils import DateTimeEncoder
from platform_config.models import PlatformConfig
from subscriber.models import PlatformSubscriber
from work.models import Works
from .models import Chapter

logger = logging.getLogger("pang5_web")
def index(request):
    return render(request, 'chapter/upload.html')
def chapter_list(request):
    if request.method != 'GET':
        return HttpResponse(status=404)
    user_id =  get_uid(request.COOKIES.get('pang5',''))
    page_num = int(request.GET.get('page_num', 0))
    l = list(
        Chapter.objects.filter(works_id__platform_subsriber_id__user_id=user_id).order_by('-id').values("works_id__name",
                                                                                        "name", 'id', 'cover_img',
                                                                                        "works_id__platform_subsriber_id__platform",
                                                                                        "ok_time","create_time","works_id__third_id", "status",
                                                                                        "fail_reason"))
    result = []
    chapter_names =list(set([i['name'] for i in l]))
    # for i in l:
    #     if i['name'] not in chapter_names:
    #         chapter_names.append(i["name"])
    # # pprint(chapter_names)
    for chapter_name in chapter_names:
        platform_data: List[Dict] = []
        for data in l:
            if data['name'] == chapter_name:
                platform_data.append(
                    {'platform': data['works_id__platform_subsriber_id__platform'], 'cover_img': data['cover_img'],
                     'ok_time': data['ok_time'], 'status': data['status'], 'id': data['id'],"third_id":data['works_id__third_id'],
                     'fail_reason': data['fail_reason'],"create_time":data['create_time']})
        work_name = [d['works_id__name'] for d in l if d['name'] == chapter_name][0]
        result.append({'chapter_name': chapter_name, 'work_name': work_name, 'platform_data': platform_data})
    return JsonResponse(result, safe=False, encoder=DateTimeEncoder)
def image_save(base_64):
    if not base_64:
        return {'status':0,'image_name':'',"pic_url":""}
    file_name = set_file_name()
    ext='.'+base_64.split(';')[0].split('/')[-1]
    image_name = 'pang5web/img/' + file_name + ext
    tmp_name = os.path.dirname(os.path.abspath(__file__)) + '/img/' + file_name + ext
    imgdata = base64.b64decode(base_64.split('base64,')[-1])
    file = open(tmp_name, 'wb')
    file.write(imgdata)
    put_object_from_file(tmp_name, image_name, 'pang5web')
    file.close()
    os.remove(tmp_name)
    return {'status':0,'image_name': image_name,"pic_url":IMG_URL}
def upload_file(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    ret = {'status': -1, 'data': None, 'error': None}
    file_name = set_file_name()
    image_name = 'pang5web/img/' + file_name
    tmp_name = os.getcwd() + '/chapter/img/' + file_name
    try:
        img = request.FILES.get('file')
        ext='.'+img.name.split(".")[-1]
        f = open(tmp_name+ext, 'wb')
        if not img:
            return JsonResponse({'status':-1,'msg':"上传失败"})
        for chunk in img.chunks(chunk_size=1024):
            f.write(chunk)
        f.flush()
        ret['status'] = 0
        ret['image_name'] = image_name+ext
        ret['pic_url'] = IMG_URL
        put_object_from_file(tmp_name+ext, image_name+ext, 'pang5web')
    except Exception as e:
        logger.error(e)
        ret['error'] = e
    finally:
        os.remove(tmp_name+ext)
        f.close()
        return JsonResponse(ret, safe=False)
def insert_rabbit(d: dict):
    credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(RABBITMQ_HOST, RABBITMQ_POST, '/', credentials))
    channel = connection.channel()
    # 声明queue
    channel.queue_declare(queue='pang5_web', durable=True)

    j = json.dumps(d)
    # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
    channel.basic_publish(exchange='',
                          routing_key='pang5_web',
                          body=j)
    logger.info("Sent success!!")
def chapter_publish(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    now=datetime.now()
    user_id =  get_uid(request.COOKIES.get('pang5',''))
    """
        代码说明 platform_info
        类型list
        信息[{"paltform":'qq',"cover":"/ad/adas.jpg",'isClocTime':0,"time":"2017-01-01 00:00:00"}]
    """
    if request.POST:
        post=request.POST
    else:
        post=json.loads(request.body)
    platform_info = post['platform_info']
    platform_info=json.loads(platform_info)
    if len(platform_info) == 0:
        j = {'status': -1, 'msg': '请提交发布平台的信息'}
        return JsonResponse(j, safe=False)
    for p in platform_info:
        if p['platform'] not in PLATFORMS:
            j = {'status': -1, 'msg': f'平台不存在'}
            return JsonResponse(j, safe=False)
    platform =[ x['platform'] for x in platform_info]
    cover={}
    clock={}
    for x in platform_info:
        cover[x['platform']]=x['cover']
        if not clock.get(x['platform'],0):
            clock[x['platform']]={}
        clock[x['platform']]['clock']=x.get("isClockTime",0)
        clock[x['platform']]['next_time']=x.get("next_time",0)
        clock[x['platform']]['time']=x.get('time','')
    blank_error_field = []
    logger.error(json.dumps(clock))
    try:
        # 作品名称
        work_name = post['work_name']
        if len(work_name) == 0:
            blank_error_field.append('作品名称')
        # 章节名称
        chapter_name = post['chapter_name']
        if len(chapter_name) == 0:
            blank_error_field.append('章节名称')
        # 章节图片,按照顺序
        chapter_imgs = post['chapter_imgs']
        if len(chapter_imgs) == 0:
            blank_error_field.append('章节图片')
        # 封面
        if 'qingdian' in platform:
            qingdian_cover_image = cover['qingdian']
            if len(qingdian_cover_image) == 0:
                blank_error_field.append('轻点封面图片')
            else:
                qingdian_cover_image=image_save(qingdian_cover_image)['image_name']
        if 'qq' in platform:
            qq_cover_image = cover['qq']
            # thrid_id = post['third_id']
            # if len(thrid_id) == 0:
            #     blank_error_field.append('作品id')
            if len(qq_cover_image) == 0:
                blank_error_field.append('腾讯动漫封面图片')
            else:
                qq_cover_image=image_save(qq_cover_image)['image_name']
        if 'u17' in platform:
            u17_cover_image = cover['u17']
            if len(u17_cover_image) == 0:
                blank_error_field.append('有妖气封面图片')
            else:
                u17_cover_image=image_save(u17_cover_image)['image_name']
        # 是否定时
        # is_publish_clock = post['is_publish_clock']
        # is_publish_clock = True if is_publish_clock == '1' else False
        # 定时时间
        qq_publish_clock_time = ''
        netEase_publish_clock_time = ''
        maimeng_publish_clock_time = ''
        if 'qq' in platform and clock['qq'].get('click',0):
            qq_publish_clock_time = clock['qq'].get('time','')
            if len(qq_publish_clock_time) == 0:
                blank_error_field.append('腾讯动漫定时发布时间')
        if 'netEase' in platform and clock['netEase'].get('clock',0):
            netEase_publish_clock_time =clock['netEase'].get('time','')
            if len(netEase_publish_clock_time) == 0:
                blank_error_field.append('网易动漫定时发布时间')
        if 'maimeng' in platform and clock['maimeng'].get('clock',0):
            maimeng_publish_clock_time = clock['maimeng'].get('time','')
            if len(maimeng_publish_clock_time) == 0:
                blank_error_field.append('麦萌漫画定时发布时间')
        if len(blank_error_field) > 0:
            j = {'status': -1, 'msg': f'{",".join(blank_error_field)}不能为空'}
            return JsonResponse(j, safe=False)
    except KeyError as e:
        logger.error(e)
        j = {'status': -1, 'msg': f'{e}参数缺失'}
        return JsonResponse(j, safe=False)
    else:
        # 腾讯动漫
        if 'qq' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='qq').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            obj, created = Chapter.objects.update_or_create(works_id=works[0], name=chapter_name,
                                                            status=PLATFORM_STATUS_PUBLISHING,
                                                            defaults={"cover_img": qq_cover_image,
                                                                      "is_publish_clock": clock['qq'].get('clock',0),
                                                                      "publish_clock_time": clock['qq'].get('time',''),
                                                                      "chapter_imgs": chapter_imgs,"create_time":now})
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        # 网易动漫
        if 'netEase' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='netEase').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            obj, created = Chapter.objects.update_or_create(works_id=works[0], name=chapter_name,
                                                            status=PLATFORM_STATUS_PUBLISHING,
                                                            defaults={"cover_img": '',
                                                                      "is_publish_clock": clock['netEase'].get('clock',0),
                                                                      "publish_clock_time": clock['netEase'].get('time',''),
                                                                      "chapter_imgs": chapter_imgs,"create_time":now})
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        # 轻点漫画
        if 'qingdian' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='qingdian').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            obj, created = Chapter.objects.update_or_create(works_id=works[0], name=chapter_name,
                                                            status=PLATFORM_STATUS_PUBLISHING,
                                                            defaults={"cover_img": qingdian_cover_image,
                                                                      "is_publish_clock": False,
                                                                      "publish_clock_time": '',
                                                                      "chapter_imgs": chapter_imgs,"create_time":now})
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        if 'maimeng' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='maimeng').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            obj, created = Chapter.objects.update_or_create(works_id=works[0], name=chapter_name,
                                                            status=PLATFORM_STATUS_PUBLISHING,
                                                            defaults={"cover_img": '',
                                                                      "is_publish_clock": clock['maimeng'].get('clock',0),
                                                                      "publish_clock_time": clock['maimeng'].get('time',0),
                                                                      "chapter_imgs": chapter_imgs,"create_time":now})
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        if 'u17' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='u17').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            obj, created = Chapter.objects.update_or_create(works_id=works[0], name=chapter_name,
                                                            status=PLATFORM_STATUS_PUBLISHING,
                                                            defaults={"cover_img": u17_cover_image,
                                                                      "is_publish_clock": clock['u17'].get('clock',0),
                                                                      "publish_clock_time": clock['u17'].get('time',0),
                                                                      "chapter_imgs": chapter_imgs,"create_time":now,"next_time":clock['u17']['next_time']})
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        msg = '提交成功'
        j = {'status': 0, 'msg': msg}
        return JsonResponse(j, safe=False)
#用户指定作品的内容
def chapter_list_for_user(request):
    if request.method !="POST":
        return HttpResponse(status=404)
    if request.POST:
        post = request.POST
    else:
        post = json.loads(request.body)
    chapter_name=post.get('chapter_name','')
    work_name=post.get('work_name','')
    if not chapter_name or not work_name:
        return JsonResponse({"status":0,"msg":"参数不得为空"},safe=False)
    user_id=get_uid(request.COOKIES.get("pang5",""))
    #根据用户　　作品名找
    # print(user_id)
    chapter_list=Chapter.objects.filter(name=chapter_name, works_id__name=work_name,works_id__platform_subsriber_id__user_id=user_id,status=-1).values('name','cover_img','is_publish_clock','publish_clock_time','chapter_imgs',"works_id__platform_subsriber_id__platform",'next_time','works_id__name','status')
    return_req={}
    for i in chapter_list:
        if not return_req.get('work_name',""):
            return_req['work_name']=i['works_id__name']
        if not return_req.get('name',""):
            return_req['name']=i['name']
        if not return_req.get('chapter_imgs',''):
            return_req['chapter_imgs']=json.loads(i['chapter_imgs'])
        if not return_req.get('platform',''):
            return_req['platform']={}
        return_req['platform'][i['works_id__platform_subsriber_id__platform']]={'cover_img':i['cover_img'],'is_publish_clock':i['is_publish_clock'],'publish_clock_time':i['publish_clock_time'],'next_time':i['next_time']}

    return_req['status']=1
    if not return_req.get("platform",''):
        return_req['platform']={}
    #用户对应作品可用的５所有的平台
    user_platform = [ x['platform_subsriber_id__platform'] for x in Works.objects.filter(platform_subsriber_id__user_id=user_id,name=work_name).values("platform_subsriber_id__platform")]
    #用户发布成功的平台
    sql_success=Chapter.objects.filter(name=chapter_name,works_id__platform_subsriber_id__user_id=user_id,works_id__name=work_name,status__in=[0,1]).values("works_id__platform_subsriber_id__platform","name")
    user_success=[x['works_id__platform_subsriber_id__platform'] for x in sql_success]
    for success in user_success:
        if success in user_platform:
            user_platform.remove(success)
    return_req['can_use_platform']=user_platform
    return_req['pic_url'] = IMG_URL
    return JsonResponse(return_req,safe=False)
def chapter_change_for_user(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    now = datetime.now()
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    """
        代码说明 platform_info
        类型list
        is_new_conver   是不是新上传的图片　１　是　　０　不是
        next_time　只有有妖气有　别的都是空,"time":"2017-01-01 00:00:00",'next_time":"2017-01-01"}]
    """
    if request.POST:
        post = request.POST
    else:
        post = json.loads(request.body)
    platform_info = post['platform_info']
    platform_info = json.loads(platform_info)
    if len(platform_info) == 0:
        j = {'status': -1, 'msg': '请提交发布平台的信息'}
        return JsonResponse(j, safe=False)
    for p in platform_info:

        if p['platform'] not in PLATFORMS:
            j = {'status': -1, 'msg': f'平台不存在'}
            return JsonResponse(j, safe=False)
    platform = [x['platform'] for x in platform_info]
    cover = {}
    clock = {}
    for x in platform_info:
        cover[x['platform']] = x.get('cover','')
        cover[x['platform']+"_is_new_cover"]=x.get('is_new_conver',0)
        if not clock.get(x['platform'], 0):
            clock[x['platform']] = {}
        clock[x['platform']]['clock'] = x.get("isClockTime", 0)
        clock[x['platform']]['next_time'] = x.get("next_time", 0)
        clock[x['platform']]['time'] = x.get('time', '')
    blank_error_field = []
    # logger.error(json.dumps(clock))
    try:
        # 作品名称
        work_name = post['work_name']
        if len(work_name) == 0:
            blank_error_field.append('作品名称')
        # 章节名称
        old_chapter_name = post.get('old_chapter_name','')
        if old_chapter_name == "":
            blank_error_field.append('旧章节名称')
        new_chapter_name = post.get('new_chapter_name','')
        if new_chapter_name == "":
            blank_error_field.append('新章节名称')
        # 章节图片,按照顺序
        chapter_imgs = post.get('chapter_imgs',0)
        if chapter_imgs == 0:
            blank_error_field.append('章节图片')
        # 封面
        if 'qingdian' in platform:
            qingdian_cover_image = cover['qingdian']
            if cover['qingdian_is_new_cover']:
                if len(qingdian_cover_image) == 0:
                    blank_error_field.append('轻点封面图片')
                else:
                    qingdian_cover_image = image_save(qingdian_cover_image)['image_name']
        if 'qq' in platform:
            qq_cover_image = cover['qq']
            # thrid_id = post['third_id']
            # if len(thrid_id) == 0:
            #     blank_error_field.append('作品id')
            if cover['qq_is_new_cover']:
                if len(qq_cover_image) == 0:
                    blank_error_field.append('腾讯动漫封面图片')
                else:
                    if cover['qq_is_new_cover']:
                        qq_cover_image = image_save(qq_cover_image)['image_name']
        if 'u17' in platform:
            u17_cover_image = cover['u17']
            if cover['u17_is_new_cover']:
                if len(u17_cover_image) == 0:
                    blank_error_field.append('有妖气封面图片')
                else:
                    u17_cover_image = image_save(u17_cover_image)['image_name']
        # 是否定时
        # is_publish_clock = post['is_publish_clock']
        # is_publish_clock = True if is_publish_clock == '1' else False
        # 定时时间
        qq_publish_clock_time = ''
        netEase_publish_clock_time = ''
        maimeng_publish_clock_time = ''
        if 'qq' in platform and clock['qq'].get('click', 0):
            qq_publish_clock_time = clock['qq'].get('time', '')
            if len(qq_publish_clock_time) == 0:
                blank_error_field.append('腾讯动漫定时发布时间')
        if 'netEase' in platform and clock['netEase'].get('clock', 0):
            netEase_publish_clock_time = clock['netEase'].get('time', '')
            if len(netEase_publish_clock_time) == 0:
                blank_error_field.append('网易动漫定时发布时间')
        if 'maimeng' in platform and clock['maimeng'].get('clock', 0):
            maimeng_publish_clock_time = clock['maimeng'].get('time', '')
            if len(maimeng_publish_clock_time) == 0:
                blank_error_field.append('麦萌漫画定时发布时间')
        if len(blank_error_field) > 0:
            j = {'status': -1, 'msg': f'{",".join(blank_error_field)}不能为空'}
            return JsonResponse(j, safe=False)
    except KeyError as e:
        logger.error(e)
        j = {'status': -1, 'msg': f'{e}参数缺失'}
        return JsonResponse(j, safe=False)
    else:
        # 删除不存在的平台信息
        # old_list=Chapter.objects.filter(name=old_chapter_name, works_id__platform_subsriber_id__user_id=user_id).values(
        #     "works_id__platform_subsriber_id__platform","id")
        # for old in old_list:
        #     if old['works_id__platform_subsriber_id__platform'] not in platform:
        #         Chapter.objects.filter(id=old['id']).delete()
        # 腾讯动漫
        #需要封面图的平台
        need_conver_platform=[x['platform'] for x  in PlatformConfig.objects.filter(has_cover_img=1).values('platform')]
        for p in platform:
            if p in need_conver_platform and not cover[p]:
                return JsonResponse({"status":0,'msg':"相关平台封面必填,请核对"},safe=False)
        if 'qq' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='qq').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            default={'name':new_chapter_name,"is_publish_clock": clock['qq'].get('clock', 0),"publish_clock_time": clock['qq'].get('time', ''),"chapter_imgs": chapter_imgs, "create_time": now}
            if cover['qq_is_new_cover']:
                default['cover_img']=qq_cover_image
            obj, created = Chapter.objects.update_or_create(works_id=works[0],name=old_chapter_name,
                                                            defaults= default)
            d = {'mysql_id': obj.id}
            # from pudb import set_trace;set_trace()
            logger.info(d)
            insert_rabbit(d)
        # 网易动漫
        if 'netEase' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='netEase').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            default = {"cover_img": '', "name": new_chapter_name,"is_publish_clock": clock['netEase'].get('clock',0),"publish_clock_time": clock['netEase'].get('time',''),"chapter_imgs": chapter_imgs, "create_time": now}
            find=Chapter.objects.filter(works_id=works[0],name=old_chapter_name).values("id")
            obj, created = Chapter.objects.update_or_create(works_id=works[0],name=old_chapter_name,defaults=default)
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        # 轻点漫画
        if 'qingdian' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='qingdian').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            default = {"name": new_chapter_name,"is_publish_clock": False,"publish_clock_time": '',"chapter_imgs": chapter_imgs, "create_time": now}
            if cover['qingdian_is_new_cover']:
                default['cover_img']=qingdian_cover_image
            obj, created = Chapter.objects.update_or_create(works_id=works[0],name=old_chapter_name,defaults=default)
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        if 'maimeng' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='maimeng').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            default={"name": new_chapter_name,"is_publish_clock": clock['maimeng'].get('clock', 0), "publish_clock_time": clock['maimeng'].get('time', 0),"chapter_imgs": chapter_imgs, "create_time": now,"next_time":''}
            obj, created = Chapter.objects.update_or_create(works_id=works[0],name=old_chapter_name,defaults=default)
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        if 'u17' in platform:
            # 校验绑定
            pss = PlatformSubscriber.objects.filter(user_id=user_id, platform='u17').all()
            if len(pss) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,您在平台{platform}下未绑定账号,请去绑定  地址: {reverse("subscriber_index")}'}
                return JsonResponse(j, safe=False)
            works = Works.objects.filter(platform_subsriber_id=pss[0], name=work_name).all()
            if len(works) == 0:
                j = {'status': -1, 'msg': f'亲爱的用户,该作品{work_name}未被添加'}
                return JsonResponse(j, safe=False)
            default={"name": new_chapter_name,"is_publish_clock": clock['u17'].get('clock', 0), "publish_clock_time": clock['u17'].get('time', 0),"chapter_imgs": chapter_imgs, "create_time": now,"next_time": clock['u17']['next_time']}
            if cover['u17_is_new_cover']:
                default['cover_img']=u17_cover_image
            obj, created = Chapter.objects.update_or_create(works_id=works[0],name=old_chapter_name,defaults=default)
            d = {'mysql_id': obj.id}
            logger.info(d)
            insert_rabbit(d)
        msg = '提交成功'
        j = {'status': 0, 'msg': msg}
        return JsonResponse(j, safe=False)